package controller;

import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.User;
import service.UserService;
import util.Laydata;
import util.Page;

import java.util.List;

@Controller
//为了让springmvc能识别这个类，需要加注解
@RequestMapping("/asyncuser")
//相当于servlet的路径

//tomcat帮忙实例化servlet
public class AsyncUserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/tolist")
    public String toList() {
        return "asyncuser/list";
    }
    @RequestMapping("/toregist")
    public String toRegist() {
        return "regist";
    }


   @RequestMapping("/list")//因为要访问user/list，所有这里写list
   @ResponseBody
    public String list(User user, @RequestParam(value ="page",defaultValue = "1") Integer currentPage, Page page,
                     @RequestParam(value="limit",defaultValue = "10") Integer pageSize, Model model){//model相当于request
        //查询数据
       int totalCount=userService.count(user);
       //偏移量
       int offset=(currentPage-1)*page.getPageSize();
      List<User> users= userService.findAll(user,offset,page.getPageSize());//拿数据
       Laydata laydata=new Laydata(0,"查询成功",totalCount,users);
       return JSON.toJSONString(laydata);


    }
    @RequestMapping("/toadd")
    public String toAdd() {
        return "user/add";
    }
    @RequestMapping("/addSave")
    public String addSave(User user) {
        int result=userService.addUser(user);
        if(result>0){
        return "redirect:/user/list/1";//重定向到list第一页
        }else {
            return "user/add";//打开页面，不加/，重定向，加/
        }
    }
    @RequestMapping("/delete/{id}")
    public String deleteById(@PathVariable("id") int id) {
        int result=userService.deleteUserById(id);
        return result>0 ? "redirect:/user/list/1":"error";
    }
    @RequestMapping("/toupdate/{id}")
    public String toUpdate(@PathVariable("id") int id, Model model) {
        //User user=userService.findById(id);
        User user=userService.findUserById(id);
        model.addAttribute("user",user);
        return "user/update";
    }
    @RequestMapping("/updateSave")
    public String updateSave(User user) {
        int result=userService.updateUser(user);
        if(result>0){
            return "redirect:/user/list/1";//重定向到list第一页
        }else {
            return "user/update";//打开页面，不加/，重定向，加/
        }
    }
    //用户密码重复校验，不写后端
    //注册数据传入
}

